'use strict';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import {
  View,
  StyleSheet,
} from 'react-native';
import {
  JDDevice,
  JDText,
  JDImage,
  JDConfirmDialog,
  JDRouter,
  JDToast,
  JDButton,
  JDLoadingView,
  JDTouchable,
  JDAudioRecorder,
  JDFileUpload,
  JDAudioPlayer
} from '@areslabs/jdreact-core-lib';
import CountDown from './CountDown';

const { NavigationBar } = JDRouter;

export default class Audio extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      audioLength: 0,                                                   //开始录音到现在的持续时间
      isRecording: false,                                                   //是否正在录音
      audioPath: null,          //路径下的文件名
      isPlaying: false,
      playLength: 0,
    }
  }

  UNSAFE_componentWillMount() {
    console.log("componentWillMount ok!!! ");
  }

  componentDidMount() {
    console.log("componentDidMount ok!!! ");
  }

  render() {
      return (
          <View style={styles.container}>
            <NavigationBar Title="语音输入页" />
            <View style={styles.body}>
              <View style={styles.recordStatus}>
                { this._renderStatus() }
              </View>
              <View style={styles.recordingImgOuter}>
                <View style={styles.recordingImgInner}>
                  {
                    this.state.isRecording ? (
                      <JDImage source={require('./images/recording.gif')} style={styles.recording} />
                    ) : (
                      <JDImage source={require('./images/recorder.png')} style={styles.recording} />
                    )
                  }
                </View>
              </View>
              <View style={styles.recordingWarning}>
                {
                  !this.state.audioPath &&  <JDText>请按住下方按钮录入语音，最长60秒</JDText>
                }
              </View>
              <View style={styles.recordingBtnWrapper}>
                {
                  this.state.audioPath && (
                    <JDTouchable onPress={this._deleteAudio}>
                      <JDText>删除音频</JDText>
                    </JDTouchable>
                  )
                }
                { this._renderAction() }
                {
                  this.state.audioPath && (
                    <JDTouchable onPress={this._uploadAudio}>
                      <JDText style={{color: '#EB452A'}}>确认发布</JDText>
                    </JDTouchable>
                  )
                }
              </View>
            </View>
          </View>
      );
  }

  _renderStatus = () => {
    if (this.state.isRecording) {
      return (
        <JDText style={{textAlign: 'center', color: '#6CC369'}}>
          <JDText>{'正在录音\n'}</JDText>
          <CountDown
            style={{fontSize: JDDevice.getFontSize(40), color: '#6CC369'}}
            duration={1000}
            value={this.state.audioLength}
            limit={this.props.recordLimit}
            onEnd={this._onTimerEnd}
            valueFormat={value => (value / 1000)}
            />
          <JDText style={{fontSize: JDDevice.getFontSize(40)}}>s</JDText>
        </JDText>
      );
    }
    if (this.state.isPlaying) {
      return (
        <JDText style={{color: '#6CC369', textAlign: 'center'}}>
          <JDText>{'录音播放中\n'}</JDText>
          <CountDown
            style={{fontSize: JDDevice.getFontSize(40), color: '#6CC369'}}
            duration={1000}
            value={this.state.playLength}
            limit={this.state.audioLength}
            onEnd={this._stopPlayAudio}
            valueFormat={value => (value / 1000)}
            />
          <JDText style={{fontSize: JDDevice.getFontSize(24)}}>s</JDText>
          <JDText style={{fontSize: JDDevice.getFontSize(24)}}>{`/${this.state.audioLength / 1000}s`}</JDText>
        </JDText>
      );
    }
    if (this.state.audioPath) {
      return (
        <JDText style={{color: '#6CC369', textAlign: 'center'}}>
          <JDText>{'录音时长\n'}</JDText>
          <JDText style={{fontSize: JDDevice.getFontSize(40)}}>{this.state.audioLength / 1000 + 's'}</JDText>
        </JDText>
      );
    }
    return null;
  }

  _renderAction = () => {
    if (!this.state.audioPath || this.state.isRecording) {
      return (
        <JDTouchable
          style={styles.recordingBtn}
          underlayColor="#AD4330"
          onPressIn={this._beginRecord}
          onPressOut={this._endRecord}>
          <JDText style={styles.recordingText}>{'按住\n说话'}</JDText>
        </JDTouchable>
      );
    }
    if (this.state.isPlaying) {
      return (
        <JDTouchable
          style={styles.recordingBtn}
          underlayColor="#AD4330"
          onPress={this._stopPlayAudio}>
          <JDText style={styles.recordingText}>暂停</JDText>
        </JDTouchable>
      );
    }
    return (
      <JDTouchable
        style={styles.recordingBtn}
        underlayColor="#AD4330"
        onPress={this._startPlayAudio}>
        <JDText style={styles.recordingText}>播放</JDText>
      </JDTouchable>
    );
  };

  _beginRecord = () => {
    if (this.state.isRecording) {
      return;
    }
    this.setState({
      isRecording: true,
      audioLength: 0,
    }, () => {
      JDAudioRecorder.startRecordingWithoutData((audioPath) => {
        this.setState({
          audioPath
        });
      }, () => {
        alert('录音失败');
      });
    });
  };

  _endRecord = () => {
    this.setState({
      isRecording: false,
    })
  };

  _onTimerEnd = (value) => {
    this.setState({
      audioLength: value,
      isRecording: false,
    }, () => {
        
      JDAudioRecorder.stopRecording((e) => {
        alert(this.state.audioPath);
      }, () => {
        alert('录音失败');
        this.setState({
          audioLength: 0,
          audioPath: null,
        });
      });
    });
  }

  _uploadAudio = () => {
    if (!this.state.audioPath || this.state.isPlaying) {
      return;
    }
    JDFileUpload.upLoadingFile({
        filepath : this.state.audioPath,
        url : 'http://outer.ase.jd.com/uploadAudioFile'
      }, () => {
        if (!this.state.audioPath) {
            return;
        }
        alert('upload success, ' + this.state.audioPath)
        this.setState({
          audioPath: null,
        });
      }, () => {
        alert('上传失败')
      },
    );
  };

  _deleteAudio = () => {
      if (!this.state.audioPath || this.state.isPlaying) {
          return;
      }
    JDAudioRecorder.deleteRecordingFile(this.state.audioPath, () => {
      this.setState({audioPath: null});
    }, () => {
      alert('删除失败');
    })
  };

  _startPlayAudio = () => {
    if (!this.state.audioPath || this.state.isPlaying) {
      return;
    }
    this.setState({isPlaying: true}, () => {
      JDAudioPlayer.startPlaying(this.state.audioPath, () => {}, () => {
        alert('播放失败')
      })
    });
  };

  _stopPlayAudio = () => {
    if (!this.state.audioPath || !this.state.isPlaying) {
      return;
    }
    this.setState({isPlaying: false}, () => {
      JDAudioPlayer.stopPlaying(() => {}, () => {
        alert('播放失败')})
    });
  };

}

Audio.defaultProps = {
  recordLimit: 60000,
};

const styles = StyleSheet.create({
  container: {
      flex: 1,
  },
  body: {
    flex: 1,
    backgroundColor: '#FAFAFA',
    justifyContent: 'flex-end',
  },

  recordStatus: {
    height: JDDevice.getRpx(283),
    justifyContent: 'center',
    alignItems: 'center',
  },

  recordingImgOuter: {
    alignSelf: 'stretch',
    flex: 1,
  },
  recordingImgInner: {
    height: JDDevice.getRpx(388),
    backgroundColor: '#F6F6F6',
    alignItems: 'center',
  },
  recording: {
    width: JDDevice.width - JDDevice.getRpx(40) * 2,
    height: JDDevice.getRpx(388),
  },

  recordingWarning: {
    paddingVertical: JDDevice.getRpx(34),
    alignItems: 'center'
  },

  recordingBtnWrapper: {
    alignItems: 'center',
    paddingVertical: JDDevice.getRpx(50),
    flexDirection: 'row',
    justifyContent: 'space-around',
  },
  recordingBtn: {
    backgroundColor: '#EB452A',
    width: JDDevice.getRpx(156),
    height: JDDevice.getRpx(156),
    borderRadius: JDDevice.getRpx(156),
    alignItems: 'center',
    justifyContent: 'center',
  },
  recordingText: {
    color: '#FFF'
  }
});
